﻿// <copyright file="T4ScriptFileGeneratorWizard.cs" company="T4 Toolbox Team">
//  Copyright © T4 Toolbox Team. All Rights Reserved.
// </copyright>

namespace T4Toolbox.VisualStudio
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using EnvDTE;

    /// <summary>
    /// Assigns T4ScriptFileGenerator custom tool to the root item  
    /// in a Visual Studio project item template.
    /// </summary>
    [CLSCompliant(false)]
    public class T4ScriptFileGeneratorWizard : ProjectItemTemplateWizard
    {
        /// <summary>
        /// Stores a list of <see cref="ProjectItem"/> objects created the the template.
        /// </summary>
        private List<ProjectItem> projectItems = new List<ProjectItem>();

        /// <summary>
        /// Runs custom wizard logic when a project item has finished generating.
        /// </summary>
        /// <param name="projectItem">
        /// The project item that finished generating.
        /// </param>
        public override void ProjectItemFinishedGenerating(ProjectItem projectItem)
        {
            this.projectItems.Add(projectItem);
        }

        /// <summary>
        /// Runs custom wizard logic when the template has been completely unfolded.
        /// </summary>
        public override void RunFinished()
        {
            string rootFileName = this.ReplacementParameters["$rootname$"];

            // If template unfolded a T4 script file, temporarily remove it from the project
            // to prevent creation of a duplicate.
            string scriptFileName = Path.ChangeExtension(rootFileName, "tt");
            ProjectItem scriptItem = this.projectItems.FirstOrDefault(projectItem => projectItem.Name == scriptFileName);
            if (scriptItem != null)
            {
                scriptItem.Remove();
            }

            // Change CustomTool property of the root file to T4ScriptFileGenerator, which
            // will reuse the T4 script file unfolded by the template.
            ProjectItem rootItem = this.projectItems.First(projectItem => projectItem.Name == rootFileName);
            Property customTool = rootItem.Properties.Item("CustomTool");
            customTool.Value = typeof(T4ScriptFileGenerator).Name;

            base.RunFinished();
        }
    }
}
